# -*- coding = utf-8 -*-
#@Time: 2020/11/19 21:11
#@Author: 卜白
#@File: util.py
#@Software: PyCharm

# 公共方法

from PIL import Image, ImageFont, ImageDraw, ImageFilter
import random
from settings import Config

# 七牛对象存储
import qiniu.config
from qiniu import Auth, put_file, etag, put_data, BucketManager

def get_random_color():
    return (random.randint(0,255),random.randint(0,25),random.randint(0,255))

'''验证码'''
def generate_image(length):
    s = 'abCDEFcdefghijk0123lmnopqrHIJKstu465vwxy789zABGUVWXYZ'
    size = (130,50)
    # 创建画布
    im = Image.new('RGB',size,color='#ccc') # color画布背景颜色
    # 创建字体
    font = ImageFont.truetype('FZSTK.TTF',size=35)
    # 创建ImageDraw对象
    draw = ImageDraw.Draw(im)
    # 绘制验证码
    code = ''
    for i in range(length):
        c = random.choice(s)
        code += c
        # x=5+random.randint(4,7)+20*i   y=random.randint(4,7)
        # text：绘制的内容    fill：颜色     font字体
        draw.text((5+random.randint(4,7)+20*i,random.randint(4,7)),
                  text=c,
                  fill=get_random_color(), # 字体颜色
                  font=font)
    # print('验证码为：', code)
    # 绘制干扰线
    for i in range(length):
        x1 = random.randint(0,130)
        y1 = random.randint(0,50/2)
        x2 = random.randint(0,130)
        y2 = random.randint(50/2,50)
        draw.line(((x1,y1),(x2,y2)),fill=get_random_color())    # fill干扰线颜色

    # 添加滤镜：BLUR、CONTOUR、EDGE_ENHANC、EDFGE_ENHANCE_MORE、EMBOSS、FIND_EDFES、SHARREN、SMOOTH、SMOOTH_MORE
    im = im.filter(ImageFilter.EDGE_ENHANCE)
    # im.show()
    return im,code


'''七牛对象存储——图片'''
def upload_qiniu(filestorage):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'qIH1JY_IO_g773w2je6nbU2TNBG1ahmHw0bcrSoO'
    secret_key = 'Z7PDL6O7um-vCA805sype4-FlDXaU03TSyjw-0g1'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    bucket_name = 'flaskhouse'  # 要上传的空间
    # 上传后保存的文件名
    filename = filestorage.filename
    randoms = random.randint(1,1000)    # 随机整数
    suffix = filename.rsplit('.')[-1]   # (图片)后缀名
    key = filename.rsplit('.')[0] + '_' + str(randoms) + '.' + suffix   # 随机拼接生成的图片名
    # key = 'my-python-logo.png'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    # 要上传文件的本地路径
    # localfile = os.path.join(Config.UPLOAD_ICON_DIR, '猪.png')
    # ret, info = put_file(token, key, localfile)
    # print(info)
    # print(ret)
    # filestorage.read()：上传二进制流
    result,info = put_data(token,key,filestorage.read())   # key随机生成的图片名
    return result,info

def delete_qiniu(filename):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'qIH1JY_IO_g773w2je6nbU2TNBG1ahmHw0bcrSoO'
    secret_key = 'Z7PDL6O7um-vCA805sype4-FlDXaU03TSyjw-0g1'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    bucket_name = 'flaskhouse'     # 要上传的空间
    # key就是要删除的文件的名字
    key = filename
    # 初始化BucketManager
    bucket = BucketManager(q)
    result,info = bucket.delete(bucket_name,key)
    return info